package com.yuncheng.oaApi.FlowController;


import com.yuncheng.entity.YcSysOrg;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.oaApi.vo.OaFlowVo;
import com.yuncheng.oaApi.vo.OaQxjspVo;
import com.yuncheng.oaApi.vo.OaReturnVo;
import com.yuncheng.oaApi.vo.Result;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.oaApi.FlowService.NewOaqxjOaFlowService;
import com.yuncheng.annotation.AutoLog;
import com.yuncheng.oaApi.busService.OaFlowNodeDbrService;
import com.yuncheng.oaApi.busService.MyLcFlowService;
import com.yuncheng.oaApi.constant.*;
import com.yuncheng.oaApi.entity.*;
import com.yuncheng.oaApi.mapper.OaQxjspFlowMapper;
import com.yuncheng.oaApi.service.*;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.oaApi.utils.GetUuIdUtils;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Api(tags = "NEW_OA-请休假管理")
@RestController
@RequestMapping("/api/spzx-oa/newflow-qxjgl")
public class NewOaQxjspFlowController {
    private static final Logger log = LoggerFactory.getLogger(NewOaQxjspFlowController.class);


    @Resource
    private OaQxjspFlowMapper oaqxjspFlowMapper;

    @Resource
    private NewOaqxjOaFlowService newOaqxjFlowService;

    @Resource
    private IOaQxjspService oaQxjspService;

    @Resource
    private IOaSpcySqsxJobService spcySqsxJobService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private IOaYcSysUserService ycSysUserService;

    @Resource
    @Lazy
    private IOaSysTzMessageService sysTzMessageService;


    @Resource
    @Lazy
    private MyLcFlowService myLcFlowService;

    @Resource
    @Lazy
    private OaFlowNodeDbrService oaFlowNodeDbrService;

    @Resource
    @Lazy
    private IOaProcessBusinessService oaProcessBusinessService;

    @Resource
    @Lazy
    private IOaYcSysOrgService ycSysOrgService;


    /**
     * 更新工龄 和 初始化信息
     */
    @AutoLog(value = "更新工龄 和 初始化信息")
    @ApiOperation(value = "更新工龄 初始化信息")
    @GetMapping("updateGl")
    public HttpResult<?> updateGl(String userid){
        YcSysUser ycSysUser = null;
        //通过参见工作时间和间隔月来 计算当前最新的参见工作年限
        List<String> user = Arrays.asList(userid.split(","));

        for (String users:user){
           ycSysUser = ycSysUserService.getById(users);
           ycSysUser = ycSysUser;
        }
        return HttpResult.ok(ycSysUser);
    }





    /**
     * 流程列表分页查询
     *
     * @param oaQxjspVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @AutoLog(value = "流程监控-分页查询")
    @ApiOperation(value = "流程监控-分页查询")
    @GetMapping("flowJkPage")
    public HttpResult flowJkPage(
            OaQxjspVo oaQxjspVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "false") boolean onlyCurrentUser) {
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaQxjspVo> page = new Page<>(pageNo, pageSize);
        oaQxjspVo.setFlcmc(OaFlowConstant.OA_QXJ_NAME);

        IPage<OaQxjspVo> list = null;
        if (StringUtils.isNotBlank(oaQxjspVo.getOaid())){
            OaQxjsp xcxxspgl = oaQxjspService.getById(oaQxjspVo.getOaid());
            if (xcxxspgl != null){
                list = oaqxjspFlowMapper.flowJkPage(page, onlyCurrentUser, user, oaQxjspVo);
            }
        }

        return HttpResult.ok(list);
    }

    /**
     * 流程列表分页查询
     *
     * @param oaQxjspVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @AutoLog(value = "流程列表-分页查询")
    @ApiOperation(value = "流程列表-分页查询")
    @GetMapping("flowJobPage")
    public HttpResult<?> flowJobPage(
            OaQxjspVo oaQxjspVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "true") boolean onlyCurrentUser) {
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        if (StringUtils.isBlank(oaQxjspVo.getFblzt())) {
            oaQxjspVo.setFblzt(OaCommonFlowConstant.BLZT_DB);
        }
        Page<OaQxjspVo> page = new Page<>(pageNo, pageSize);
        oaQxjspVo.setFlcmc(OaFlowConstant.OA_QXJ_NAME);
        IPage<OaQxjspVo> list = oaqxjspFlowMapper.flowJobPage(page, onlyCurrentUser, user, oaQxjspVo);
        return HttpResult.ok(list);
    }


    /**
     * 我的已办
     */
    @AutoLog(value = "流程列表-我的已办")
    @ApiOperation(value = "流程列表-我的已办")
    @GetMapping("myJobPage")
    public HttpResult<?> myJobPage(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            OaQxjspVo oaQxjspVo) {

        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaQxjspVo> page = new Page<>(pageNo, pageSize);
        IPage<OaQxjspVo> list = oaqxjspFlowMapper.myYbFlowPage(page, true, user, oaQxjspVo);
        return HttpResult.ok(list);
    }

    /**
     * 数据修订
     */
    @AutoLog(value = "列表-数据修订")
    @ApiOperation(value = "列表-数据修订")
    @GetMapping("Pagesjxd")
    public HttpResult<?> Pagesjxd(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            OaQxjspVo oaQxjspVo) {

        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaQxjspVo> page = new Page<>(pageNo, pageSize);
        IPage<OaQxjspVo> list = oaqxjspFlowMapper.myYbFlowPage(page, false, user, oaQxjspVo);
        return HttpResult.ok(list);
    }

    /**
     * @param:
     * @Description: 更新年度信息
     * @auther: lhb
     * @date: 2023/9/14 17:42
     */
    @AutoLog(value = "更新年度信息 ")
    @ApiOperation(value = "更新年度信息")
    @GetMapping("myndxx")
    public HttpResult myndxx() {
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (currentUser == null) {
            return HttpResult.error("当前登录已失效，请重新登录");
        }
        Result getndxx = newOaqxjFlowService.getndxx();
        return HttpResult.ok(getndxx);
    }

    /**
     * @param:
     * @Description: 请假说明
     * @auther: lhb
     * @date: 2023/9/14 17:42
     */
    @AutoLog(value = "请假说明")
    @ApiOperation(value = "请假说明")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "qxlx", value = "请假类型"),
            @ApiImplicitParam(name = "ts", value = "天数"),
            @ApiImplicitParam(name = "njdbj", value = "是否拿年假抵病假：是/否")
    })
    @GetMapping("myqxsm")
    public HttpResult myqxsm(String qxlx,Integer ts,String njdbj) {
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (currentUser == null) {
            return HttpResult.error("当前登录已失效，请重新登录");
        }
        Result qjsm = newOaqxjFlowService.getqjxx(qxlx,ts,njdbj);
        return HttpResult.ok(qjsm);
    }


    /**
     * @param:
     * @Description: 手动转结年休假
     * @auther: lhb
     * @date: 2023/9/15 10:53
     */
    @AutoLog(value = "手动转结年休假")
    @ApiOperation(value = "手动转结年休假")
    @GetMapping("sdzjts")
    public HttpResult sdzjts(String userids) throws InvocationTargetException, IllegalAccessException {
        Result getqjxx = newOaqxjFlowService.zjNxj(userids);
        if (!getqjxx.isSuccess()) {
            getqjxx.getMessage();
        }
        return HttpResult.ok(getqjxx);
    }

    /**
     * @param:
     * @Description: 手动清零转结年休假
     * @auther: lhb
     * @date: 2023/9/15 10:53
     */
    @AutoLog(value = "手动清零转结年休假")
    @ApiOperation(value = "手动清零转结年休假")
    @GetMapping("sdqlzjts")
    public HttpResult sdqlzjts(String userids) {
        Result getqjxx = newOaqxjFlowService.deletelZjnj(userids);
        if (!getqjxx.isSuccess()) {
            getqjxx.getMessage();
        }
        return HttpResult.ok(getqjxx);
    }

    /**
     * 获取人事意见
     * @param oaid
     * @return
     */
    @AutoLog(value = "获取人事意见")
    @ApiOperation(value = "获取人事意见")
    @GetMapping("rsyj")
    public HttpResult rsyj(String oaid) {

        OaQxjsp oaqxjsp =  oaQxjspService.getById(oaid);
        String fuserid = oaqxjsp.getFuserid();
        YcSysUser sysUser = ycSysUserService.getById(fuserid);
        String fdqnjnd = sysUser.getFdqnjnd();

        BigDecimal yxts = new BigDecimal(sysUser.getFnxjyxts()); //应休天数
        BigDecimal syts = new BigDecimal(sysUser.getFnxjsyts()); //剩余天数
        BigDecimal yxtss = yxts.subtract(syts); //已休天数
        BigDecimal sytss = syts.subtract(new BigDecimal(oaqxjsp.getFts()));

        String nr = "其"+fdqnjnd+"年年休假"+sysUser.getFnxjyxts()+"天，已休"+yxtss+"天，扣除此次休假"+oaqxjsp.getFts()+"天，"+"尚余"+sytss+"天未休。";


        return HttpResult.ok(nr);
    }


    @AutoLog(value = "发起请休假")
    @ApiOperation(value = "发起请休假")
    @PostMapping(value = "initBzFlow")
    public HttpResult<?> initBzFlow(@RequestBody OaQxjsp oaQxjsp) throws ParseException {
        String oaid = "";
        //当前人的id
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (currentUser == null) {
            return HttpResult.error("当前登录已失效，请重新登录");
        }
        if (StringUtils.isNotBlank(oaQxjsp.getId())) {
            OaQxjsp oaids = oaQxjspService.getById(oaQxjsp.getId());
            ConvertUtils.register(new DateConvert(), Date.class);
            try {
                BeanUtils.populate(oaids, BeanUtils.describe(oaQxjsp));
            } catch (IllegalAccessException e) {
                log.error("出错-保存事项【非法访问异常】,{}", e.getMessage());
            } catch (InvocationTargetException e) {
                log.error("出错-保存事项【调用TargetException】,{}", e.getMessage());
            } catch (NoSuchMethodException e) {
                log.error("出错-找不到可用方法", e.getMessage());
            }
            oaid = oaQxjsp.getId();

            // Date日期单独做处理
            oaids.setFuserid(currentUser.getId());
            oaQxjspService.updateById(oaids);
        } else {
            oaid = GetUuIdUtils.ReplaceUuId();

            YcSysUser user = ycSysUserService.getById(currentUser.getId());
            oaQxjsp.setId(oaid);
            oaQxjsp.setFxm(currentUser.getName());
            oaQxjsp.setFuserid(currentUser.getId());
            //部门
            String orgId = ycSysUserService.getUserZbmByUserId(currentUser.getId());
            YcSysOrg ycSysOrg = ycSysOrgService.getById(orgId);
            oaQxjsp.setFbm(ycSysOrg.getOrgName());

            oaQxjsp.setFzw(user.getFzw());
            oaQxjsp.setFlczt(OaCommonFlowConstant.FLOW_LCZB);


            if (StringUtils.isBlank(oaQxjsp.getFts())){
                throw new RuntimeException("天数参数丢失");
            }
            oaQxjsp.setFts(oaQxjsp.getFts());
            oaQxjspService.save(oaQxjsp);
        }

        /**
         * @Author: lhb
         * @Description : 是否发起流程   如果是开始申请就跳转流程
         *               在这里设置 nextnodeId 指定下个环节节点id 做当前跳转流程的判断，然后设置变量接收环节的值，写到 nextnodeId 中
         * @DateTime:
         * @Params: Fsffqlc
         */
        String msg = "保存成功";
        String lcmbCode = OaFlowConstant.OA_QXJ;
        OaJobEntity job = new OaJobEntity();
        // 初始化流程
        Result result = newOaqxjFlowService.createProcess(lcmbCode,oaid, currentUser);
        //做一次规则校验 如果查到此oaid 在表中已经插入 那就执行更新
        OaQxjsp oaQxjsp1 = oaQxjspService.getById(oaid);
        List<OaProcessBusiness> oaProcessBusinessList = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                .eq(OaProcessBusiness::getFpid, oaid));
        String bt =  currentUser.getName()+"提交的请休假"; //标题
        String zy = "请休假类型:"+oaQxjsp1.getFqjlx()+"\n"
                + "开始时间:["+ oaQxjsp1.getFqjkssj()+"]"+"\n"
                +"结束时间:["+ oaQxjsp1.getFqjjssj() + "]"+"\n"
                + "时长:"+ oaQxjsp1.getFts()+"天";
        if (oaProcessBusinessList.size() == 0){
            //初始化的时候 像 流程业务主表添加拼接初始化数据
            oaProcessBusinessService.addProcess(oaid,zy,bt,lcmbCode,OaFlowConstant.OA);

        }else {
            String id = oaProcessBusinessList.get(0).getId();  //当前已经插入的主键id 然后更新 摘要信息
            OaProcessBusiness oaProcessBusiness = oaProcessBusinessService.getById(id);
            oaProcessBusiness.setFzy(zy);
            oaProcessBusinessService.updateById(oaProcessBusiness);

        }


        if (!result.isSuccess()) {
            return HttpResult.error(result.getMessage());
        } else {
             job = (OaJobEntity) result.getResult();
            if (job != null) {
                // 是否提交流程
                if (StringUtils.isBlank(oaid)) {
                    return HttpResult.error("参数丢失");
                }
                String nextnodeId = "";
                if (StringUtils.isNotBlank(oaQxjsp.getFsffqlc()) && oaQxjsp.getFsffqlc().equals(OaCommonFlowConstant.SFFQLC_YES)) {
                    OaQxjsp oaQxjsp2 =  oaQxjspService.getById(oaQxjsp.getId());

                    if (StringUtils.isBlank(oaQxjsp2.getFbm())){
                        return HttpResult.error("用户部门为空，请完善个人信息部门栏");
                    }
                    if (StringUtils.isBlank(oaQxjsp2.getFlczt())) {
                        oaQxjsp2.setFlczt(OaCommonFlowConstant.FLOW_LCZB);
                    }
                    String fuserid = oaQxjsp2.getFuserid();
                    YcSysUser user = ycSysUserService.getById(fuserid);

                    //在提交流程的时候，如果请休假类型为年休假且为流程在办的时候，则只能有一条数据
                    boolean onenxj = newOaqxjFlowService.onenxj(fuserid);
                    if (!onenxj) {
                        return HttpResult.error("有未办结的年休假申请，请先办结未办结的年休假申请，在申请");
                    }
                    BigDecimal fnxjsyts = new BigDecimal(user.getFnxjsyts());
                    int i = fnxjsyts.compareTo(BigDecimal.valueOf(0));
                    if (oaQxjsp2.getFqjlx().equals(OaqxjOaFlowConstants.QXJ_NJ) && i == 0) {
                        return HttpResult.error("您本年度年假已休完，不能再申请年假，如有疑问请联系人事处！");
                    }
                    BigDecimal ts = new BigDecimal(oaQxjsp2.getFts());
                    BigDecimal syts = new BigDecimal(user.getFnxjsyts());
                    int i1 = ts.compareTo(syts);
                    if (i1 > 0  && oaQxjsp2.getFqjlx().equals(OaqxjOaFlowConstants.QXJ_NJ)) {
                        return HttpResult.error("您的请假天数大于您本年度的年假剩余天数，请修改。如有疑问请联系人事处");
                    }

                    List<OaSysFlowNode> oaSysFlowNodesDwldsp = newOaqxjFlowService.getNodeList(OaFlowConstant.QXJ_HJMC_DWLDSP);
                    List<OaSysFlowNode> oaSysFlowNodesRssp = newOaqxjFlowService.getNodeList(OaFlowConstant.QXJ_HJMC_RSSP);

                    //如果是中心副主任提交 下一环节应该为 单位领导审批
                    if (oaQxjsp2.getFbm().contains(OaCommonFlowConstant.ORG_NAME_ZXFZR)) {
                        nextnodeId = oaSysFlowNodesDwldsp.get(0).getId();

                    } else if (oaFlowNodeDbrService.brksfzr()) {
                        nextnodeId = oaSysFlowNodesRssp.get(0).getId();
                    } else {
                        nextnodeId = "";
                    }
                    Result result1 = newOaqxjFlowService.passJob(oaid, job.getId(), "同意", nextnodeId, "");
                    if (!result1.isSuccess()) {
                        return HttpResult.error(result.getMessage());
                    }
                    msg = "提交成功";
                    //提交完成后 更新待办信息
                    sysTzMessageService.tjMessage(oaid);

                    List<OaProcessBusiness> oaProcessBusinessList1 = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                                                                                                        .eq(OaProcessBusiness::getFpid, oaid));
                    OaProcessBusiness oaProcessBusiness = oaProcessBusinessList1.get(0);
                    OaProcessBusiness byId1 = oaProcessBusinessService.getById(oaProcessBusiness.getId());

                    String upatezy = "请休假类型:"+oaQxjsp2.getFqjlx()+"\n"
                            + "开始时间:["+ oaQxjsp2.getFqjkssj()+"]"+"\n"
                            +"结束时间:["+ oaQxjsp2.getFqjjssj() + "]"+"\n"
                            + "时长:"+ oaQxjsp2.getFts()+"天";
                    byId1.setFzy(upatezy);
                    byId1.setFsfkch(0);
                    byId1.setFcshdb(OaFlowConstant.FLOW_BLZT_YB);
                    oaProcessBusinessService.updateById(byId1);

                    myLcFlowService.recall(oaid);

                }
            }
        }
        HashMap map = new HashMap();
        map.put("msg",msg);
        map.put("oaMap",oaQxjsp);
        map.put("jobMap",job);
        return HttpResult.ok(map);
    }

    /**
     * 请休假保存接口
     */
    @AutoLog(value = "请休假保存接口")
    @ApiOperation(value = "请休假保存接口")
    @PostMapping(value = "/saveFlow")
    public HttpResult<?> saveFlow(@RequestBody OaFlowVo oaFlowVo) throws ParseException {
        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SAVE; // 保存

        String jobId = oaFlowVo.getJobid(); // 当前流程任务id
        String oaid = oaFlowVo.getOaid(); // 当前办公主键id
        String opinion = oaFlowVo.getOpinion(); // 办理意见

        if (StringUtils.isBlank(jobId)) {
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }
        // 流程处理
        Result httpResult = newOaqxjFlowService.handleFlow(oaFlowVo, null, jobId, oaid, submitType, opinion);
        if (!httpResult.isSuccess()) {
            return HttpResult.error(httpResult.getMessage());
        }
        Map map = new HashMap();
        HttpResult<Object> res = new HttpResult<>(true);
        res.setMessage("保存成功");
        res.setResult(map);
        return res;
    }

    /**
     * 请休假提交接口
     */
    @AutoLog(value = "请休假提交接口")
    @ApiOperation(value = "请休假提交接口")
    @PostMapping(value = "/submitFlow")
    public HttpResult<?> submitFlow(@RequestBody OaFlowVo oaFlowVo) throws ParseException {

        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SUBMIT; // 提交

        String jobId = oaFlowVo.getJobid();
        String oaid = oaFlowVo.getOaid();
        String opinion = oaFlowVo.getOpinion();
        OaQxjsp oaId = oaQxjspService.getById(oaid);
        OaJobEntity jobid = spcySqsxJobService.getById(jobId);

        if (jobid.getFhjmc().equals(OaLgqsOaFlowConstants.HJMC_XJ)) {

        } else {
            oaId.setFlczt(OaCommonFlowConstant.FLOW_LCZB);
        }
        if (StringUtils.isBlank(oaId.getFsffqlc())) {
            oaId.setFsffqlc(OaCommonFlowConstant.SFFQLC_YES);
        }

        oaQxjspService.updateById(oaId);
        if (StringUtils.isBlank(oaid)) {
            return HttpResult.error("办公主键id参数丢失，请联系管理员");
        }

        if (StringUtils.isBlank(jobId)) {
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }
        /* if (StringUtils.isBlank(opinion)){
            return HttpResult.error("请填写办理意见");
        }*/
        OaJobEntity nowJob = null;
        Result httpResult1 = newOaqxjFlowService.handleFlow(oaFlowVo, nowJob, jobId, oaid, submitType, opinion);
        if (!httpResult1.isSuccess()) {
            return HttpResult.error(httpResult1.getMessage());
        }
        List<OaProcessBusiness> oaProcessBusinessList1 = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                .eq(OaProcessBusiness::getFpid, oaid));
        OaProcessBusiness oaProcessBusiness = oaProcessBusinessList1.get(0);
        OaProcessBusiness byId1 = oaProcessBusinessService.getById(oaProcessBusiness.getId());
        byId1.setFsfkch(0);
        byId1.setFcshdb(OaFlowConstant.FLOW_BLZT_YB);
        oaProcessBusinessService.updateById(byId1);
        //提交完成后 更新待办信息
        sysTzMessageService.tjMessage(oaid);
        myLcFlowService.recall(oaid);
        return HttpResult.ok("提交成功");
    }

    /**
     * 查询当前流程任务详情-通过当前流程任务id
     */
    @AutoLog(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiOperation(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiImplicitParam(value = "jobid", name = "流程任务id", required = true)
    @GetMapping(value = "queryJobByJobId")
    public HttpResult<?> queryJobByJobId(@RequestParam("jobid") String jobid) {
        if (StringUtils.isBlank(jobid)) {
            return HttpResult.error("流程任务id不能为空");
        }
        Map map = newOaqxjFlowService.getJobConcernByJobId(jobid);
        return HttpResult.ok(map);
    }


    /**
     * 获取已办列表-通过当前流程id-自定义退回
     *
     * @param jobid
     * @return
     */
    @AutoLog(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiOperation(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobid", value = "流程任务id"),
            @ApiImplicitParam(name = "isZdhj", value = "是否指定环节，默认：true，指定")
    })
    @GetMapping(value = "queryAllYbJob")
    public HttpResult<?> queryAllYbJob(@RequestParam(value = "jobid", defaultValue = "") String jobid,
                                       @RequestParam(value = "isZdhj", defaultValue = "true") boolean isZdhj) {
        List<Map<String, String>> currentJobPrevious = newOaqxjFlowService.getCurrentJobPrevious(jobid, isZdhj);
        return HttpResult.ok(currentJobPrevious);
    }
    /**
     * 退回环节
     *
     * @return
     */
    @AutoLog(value = "自定义-退回环节")
    @ApiOperation(value = "自定义-退回环节")
    @PostMapping(value = "returnUpperzdyFlowJob")
    public HttpResult<?> returnUpperzdyFlowJob(@RequestBody OaReturnVo oaReturnVo) {
        newOaqxjFlowService.returnZdJob(oaReturnVo);

        //退回更新通知信息
        OaJobEntity oaJobEntity = spcySqsxJobService.getById(oaReturnVo.getJobid());
        String fpid = oaJobEntity.getFpid();
        sysTzMessageService.endMessage(fpid,false,false,true);

        return HttpResult.ok("退回成功");
    }





    @AutoLog(value = "删除请休假流程")
    @ApiOperation(value = "删除请休假流程")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobids", value = "流程任务id,逗号分割", required = true)
    })
    @DeleteMapping(value = "deleteLgqsFlowJob")
    public HttpResult<?> deleteLgqsFlowJob(@RequestParam(value = "jobids") String jobids) {
        if (StringUtils.isBlank(jobids)) {
            return HttpResult.error("参数不能为空");
        }
        List<String> jobIdList = Arrays.asList(jobids.split(","));
        String logNr = "";
        Map<String, Object> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(jobIdList)) {
            List<OaJobEntity> jobList = spcySqsxJobService.listByIds(jobIdList);
            if (CollectionUtils.isNotEmpty(jobList)) {
                for (OaJobEntity job : jobList) {
                    spcySqsxJobService.removeById(job.getId());
                    OaQxjsp oaQxjsp = oaQxjspService.getById(job.getFpid());
                    if (oaQxjsp != null) {
                        oaQxjspService.removeById(job.getFpid());

                        logNr = "删除请休假流程" + job.getFhjmc() + ": ";
                        map = ObjectToMapUtils.objectToMap(oaQxjsp);
                        logNr += LogUtils.MapToStringMethod(map);

                        spcyLogService.addLogs(job.getFhjmc(), logNr, job.getFpid(), OaLogConstant.LOGS_OA_LGQS, OaCommonFlowConstant.LOGS_SYS_TYPE_SC);
                    }
                }
            }
        }

        return HttpResult.ok("删除成功");
    }

    @AutoLog(value = "更新连休的次数")
    @ApiOperation(value = "更新连休的次数")
    @GetMapping(value = "updateLxcs")
    public HttpResult<?> updateLxcs( String oaid) throws ParseException {

        Result updatelxzt = newOaqxjFlowService.updatelxzt(oaid);
        return HttpResult.ok(updatelxzt);


    }


    @AutoLog(value = "测试实际请假天数")
    @ApiOperation(value = "测试实际请假天数")
    @GetMapping(value = "cssjqjts")
    public HttpResult<?> cssjqjts(String oaid){
        OaQxjsp oaQxjsp = oaQxjspService.getById(oaid);
        String fqjjssj = oaQxjsp.getFqjjssj();


        String fqjkssj = oaQxjsp.getFqjkssj();

        String fxjqrxs = oaQxjsp.getFxjqrxs();

        long qjkssjtime = DateConversionUtils.StringToDate(fqjkssj).getTime();
        long xjqrsjtime = DateConversionUtils.StringToDate(oaQxjsp.getFxjqrsj()).getTime();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        LocalTime nineAm = LocalTime.of(9, 0);

        String fqjksxs = oaQxjsp.getFqjksxs(); //请假开始时间
        //如果请休假结束时间 > 销假时间 那就代表着提前销假
        if (DateConversionUtils.StringToDate(fqjjssj).getTime() > DateConversionUtils.StringToDate(oaQxjsp.getFxjqrsj()).getTime()){
            long ts = 0;
            //如果提前销假只以销假时间和请假开始时间开始算
            long jltshms =  xjqrsjtime - qjkssjtime;
            if (jltshms != 0){
                ts = jltshms / OaCommonFlowConstant.T_YQ / OaCommonFlowConstant.T_MS;
            }
            //如果开始时间和结束时间想等
            if(jltshms == 0){

                if (fqjksxs.equals(OaCommonFlowConstant.QXJSQ_SW)){
                    //如果请假开始小时的时间是上午，那么获取的销假小时的范围
                    //如果销假小时的的范围是 9点之前 那么实际请假时间是0
                    LocalTime givenTime = LocalTime.parse(fxjqrxs, formatter);
                    boolean before = givenTime.isBefore(nineAm);
                    if (before){
                        oaQxjsp.setFsjqjsj("0");
                        //如果不是那就向下判断
                    }else {
                        boolean timeBetween = DateConversionUtils.isTimeBetween(fxjqrxs, OaCommonFlowConstant.QXJSQ_FWSW, OaCommonFlowConstant.QXJSQ_FWZW);
                        if (timeBetween){
                            oaQxjsp.setFsjqjsj("0.5");
                        }else {
                            boolean timeBetween1 = DateConversionUtils.isTimeBetween(fxjqrxs, OaCommonFlowConstant.QXJSQ_FWZW, OaCommonFlowConstant.QXJSQ_FWXW);
                            if (timeBetween1){
                                oaQxjsp.setFsjqjsj("1");
                            }
                        }
                    }
                }
            }
            if(ts == 1){
                if (fqjksxs.equals(OaCommonFlowConstant.QXJSQ_SW)){
                    //如果请假开始小时的时间是上午，那么获取的销假小时的范围
                    //如果销假小时的的范围是 9点之前 那么实际请假时间是0
                    LocalTime givenTime = LocalTime.parse(fxjqrxs, formatter);
                    boolean before = givenTime.isBefore(nineAm);
                    if (before){
                        oaQxjsp.setFsjqjsj("1");
                        //如果不是那就向下判断
                    }else {
                        boolean timeBetween = DateConversionUtils.isTimeBetween(fxjqrxs, OaCommonFlowConstant.QXJSQ_FWSW, OaCommonFlowConstant.QXJSQ_FWZW);
                        if (timeBetween){
                            oaQxjsp.setFsjqjsj("1.5");
                        }else {
                            boolean timeBetween1 = DateConversionUtils.isTimeBetween(fxjqrxs, OaCommonFlowConstant.QXJSQ_FWZW, OaCommonFlowConstant.QXJSQ_FWXW);
                            if (timeBetween1){
                                oaQxjsp.setFsjqjsj("2");
                            }
                        }
                    }
                }
            }
            if (ts > 1){
                if (fqjksxs.equals(OaCommonFlowConstant.QXJSQ_SW)){
                    //如果请假开始小时的时间是上午，那么获取的销假小时的范围
                    //如果销假小时的的范围是 9点之前 那么实际请假时间是0
                    LocalTime givenTime = LocalTime.parse(fxjqrxs, formatter);
                    boolean before = givenTime.isBefore(nineAm);
                    if (before){
                        long l = ts + 1 - 1;
                        oaQxjsp.setFsjqjsj(String.valueOf(l));
                        //如果不是那就向下判断
                    }else {
                        boolean timeBetween = DateConversionUtils.isTimeBetween(fxjqrxs, OaCommonFlowConstant.QXJSQ_FWSW, OaCommonFlowConstant.QXJSQ_FWZW);
                        if (timeBetween){
                            Double l = ts + 1.5 - 1;
                            oaQxjsp.setFsjqjsj(String.valueOf(l));
                        }else {
                            boolean timeBetween1 = DateConversionUtils.isTimeBetween(fxjqrxs, OaCommonFlowConstant.QXJSQ_FWZW, OaCommonFlowConstant.QXJSQ_FWXW);
                            if (timeBetween1){
                                long l = ts + 2 - 1;
                                oaQxjsp.setFsjqjsj(String.valueOf(l));
                            }
                        }
                    }
                }
            }
        }

        oaQxjspService.updateById(oaQxjsp);
        return HttpResult.ok();
    }


    /**
     * 实际请休假列表
     */
    @AutoLog(value = "实际请休假列表")
    @ApiOperation(value = "实际请休假列表")
    @GetMapping("sjqjPage")
    public HttpResult sjqjPage(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){
        LambdaQueryWrapper<OaQxjsp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OaQxjsp :: getFlczt, OaCommonFlowConstant.FLOW_LCJS);
        Page<OaQxjsp> page = new Page<>(pageNo, pageSize);
        Page<OaQxjsp> page1 = oaQxjspService.page(page, queryWrapper);
        return  HttpResult.ok(page1);
    }





}
